package com.rpa.server.servicerpaserver.expose.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rpa.secure.servicerpasecure.common.result.Result;
import com.rpa.server.servicerpaserver.crawler.entity.Clazz;
import com.rpa.server.servicerpaserver.crawler.entity.Work;
import com.rpa.server.servicerpaserver.crawler.service.WorkService;
import com.rpa.server.servicerpaserver.expose.dto.ActiveDto;
import com.rpa.server.servicerpaserver.expose.dto.WorkDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @className: WorkController
 * @author: lzt
 * @date: 2025/2/14 15:54
 * @Version: 1.0
 * @description:
 */
@RestController
@RequestMapping("/api/work")
@Slf4j
@Tag(name = "本系统作业相关接口", description = "WorkController")
public class WorkController {
    @Autowired
    private WorkService workService;
    @PostMapping("/getWorkEnum")
    @Operation(summary = "获取作业枚举", description = "getWorkEnum")
    public Result<List<Work>> getWorkEnum(@RequestBody WorkDto workDto) {
        QueryWrapper<Work> workLambdaQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Work> eq = workLambdaQueryWrapper.select("DISTINCT account_id as accountId,course_id as courseId,clazz_id as clazzId,work_name as workName,work_time as workTime,proportion, is_enabled as isEnabled")
                .lambda()
                .eq(Work::getAccountId, workDto.getAccountId())
                .eq(Work::getCourseId, workDto.getCourseId())
                .eq(Work::getClazzId, workDto.getClazzId());
        List<Work> list = workService.list(eq);
        return Result.success(list);
    }



    @PostMapping("/updateWorkEnum")
    @Operation(summary = "更新作业枚举", description = "updateWorkEnum")
    public Result<Boolean> updateWorkEnum(@RequestBody List<Map> workEnumList) {
        if(CollUtil.isEmpty(workEnumList)){
            return Result.error("未选中任何一行！");
        }
        boolean b =workService.updateWorkEnum(workEnumList);
        return Result.success(b);
    }

    @PostMapping("/getWorkList")
    @Operation(summary = "获取作业列表", description = "getWorkList")
    public Result<List<Map<String, Object>>> getWorkList(@RequestBody WorkDto workDto) {
        if (Objects.isNull(workDto)){
            return Result.error("参数不能为空！");
        }
        List<Map<String, Object> > list = workService.getWorkList(workDto);
        return Result.success(list);
    }

    @PostMapping(value = "/export/downloadWorkList")
    @Operation(summary = "下载作业列表", description = "downloadWorkList")
    public void downloadWorkList(@RequestBody WorkDto workDto, HttpServletResponse response) {
        if (workDto == null || workDto.getFileName() == null || workDto.getFileName().trim().isEmpty()) {
            log.warn("下载请求参数无效: {}", workDto);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400 Bad Request
            return;
        }

        try {
            // 设置 Content-Type 和 Content-Disposition
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            // 文件名的 URL 编码
            String fileName = URLEncoder.encode(workDto.getFileName() + "作业", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入 Excel 文件流到响应输出流
            EasyExcel.write(response.getOutputStream())
                    .head(workService.head())
                    .sheet(workDto.getFileName())
                    .doWrite(workService.dataList(workDto));

        } catch (Exception e) {
            log.error("下载签到活动列表失败, activeDto: {}", workDto, e); // 记录异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500 Internal Server Error
        } finally {
            // 确保关闭输出流
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                log.error("关闭输出流失败", e);
            }
        }
    }


}
